package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.FoodMapper;
import com.example.demo.model.Food;
import com.example.demo.service.FoodService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static org.springframework.transaction.annotation.Propagation.NESTED;
import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;

/**
 * @author Shanks
 * @date 2020-10-23
 */
@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements FoodService {

    private final static DateTimeFormatter FORMATTER =  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Resource
    private FoodMapper foodMapper;

    @Override
    @Transactional(propagation = REQUIRES_NEW, rollbackFor = Exception.class)
    public void saveRequiresNew() {
        Food food = new Food();
        food.setCode(LocalDateTime.now().format(FORMATTER));
        food.setName("REQUIRES_NEW, 无异常");
        food.setOriginPlace("上海");
        foodMapper.insert(food);
    }

    @Override
    @Transactional(propagation = REQUIRES_NEW, rollbackFor = Exception.class)
    public void saveRequiresNewWithEx() {
        Food food = new Food();
        food.setCode(LocalDateTime.now().format(FORMATTER));
        food.setName("REQUIRES_NEW, 且异常");
        food.setOriginPlace("上海");
        foodMapper.insert(food);

        int i = 1 / 0;
        System.out.println(i);
    }

    @Override
    @Transactional(propagation = NESTED, rollbackFor = Exception.class)
    public void saveNested() {
        Food food = new Food();
        food.setCode("200");
        food.setName("NESTED");
        food.setOriginPlace("上海");
        foodMapper.insert(food);
    }

    @Override
    @Transactional(propagation = NESTED, rollbackFor = Exception.class)
    public void saveNestedWithEx() {
        Food food = new Food();
        food.setCode("500");
        food.setName("NESTED, 抛异常");
        food.setOriginPlace("上海");
        foodMapper.insert(food);

        int i = 1 / 0;
        System.out.println(i);
    }
}